﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FastMath;
using Tao.OpenGl;
using PocketEngine.Engine;
namespace PocketEngine.Geometry
{
    public class pGeometry 
    {
        public List<FastMath.Vector2> Points = new List<FastMath.Vector2>();
    }
    public class pTriangle
    {
        public Vector2 p0, p1, p2;
        public pColor c0, c1, c2;
        public Vector2 tex0, tex1, tex2;
        public void QuickDraw(float dx,float dy)
        {
            Gl.glColor4f(c0.R, c0.G, c0.B, c0.A);
            Gl.glTexCoord2f(tex0.X, tex0.Y);
            Gl.glVertex2f(p0.X+dx, p0.Y+dy);
            Gl.glColor4f(c1.R, c1.G, c1.B, c1.A);
            Gl.glTexCoord2f(tex1.X, tex1.Y);
            Gl.glVertex2f(p1.X+dx, p1.Y+dy);
            Gl.glColor4f(c2.R, c2.G, c2.B, c2.A);
            Gl.glTexCoord2f(tex2.X, tex2.Y);
            Gl.glVertex2f(p2.X+dx, p2.Y+dy);
        }
    }
    public class pTriangles : pGeometry
    {
        public pTriangles()
        {
        }
        private float sy=9999, by=-99999;
        public void AddPoint(float x, float y)
        {
            if (y < sy) sy = y;
            if (y > by) by = y;
            Points.Add(new Vector2(x, y));
        }
        public void AddPoint(FastMath.Vector2 point)
        {
            Points.Add(point);
        }
        public List<pTriangle> Triangles = null;
        public void QuickDraw(float dx, float dy)
        {
            Gl.glEnable(Gl.GL_BLEND);
            Gl.glBlendFunc(Gl.GL_SRC_ALPHA, Gl.GL_ONE_MINUS_SRC_ALPHA);

            Gl.glBegin(Gl.GL_TRIANGLES);
            foreach (var t in Triangles)
            {
                t.QuickDraw(dx, dy);
            }
            Gl.glEnd();
        }
        public void ConvertToTris()
        {
            Triangles = new List<pTriangle>();
            Vector2[] verts = null;
            int[] indices = null;
            Triangulator.Triangulator.Triangulate(Points.ToArray(), Triangulator.WindingOrder.Clockwise, out verts, out indices);
            for (int i = 0; i < indices.Length; i+=3)
            {
                if (i > indices.Length - 1)
                {
                    continue;
                }
               
                pTriangle tri = new pTriangle();
                tri.p0 = verts[indices[i]];
                tri.p1 = verts[indices[i + 1]];

                tri.p2 = verts[indices[i + 2]];
                tri.c0 = genCol(tri.p0);
                tri.c1 = genCol(tri.p1);
                tri.c2 = genCol(tri.p2);

                Triangles.Add(tri);
             }
            
        }
        public pColor genCol(Vector2 p)
        {
            float yo = p.Y - sy;
            float range = by - sy;
            float v = yo / range;
            v = v + 0.25f;
            return new pColor(0.765f*v, 0.7f * v, 0.9f * v, 0.25f+0.85f * v);
        }
    }
}
